package com.example.ywr.controller;

import com.example.ywr.common.Result;
import com.example.ywr.dto.LoginRequest;
import com.example.ywr.dto.LoginResponse;
import com.example.ywr.dto.RegisterRequest;
import com.example.ywr.entity.User;
import com.example.ywr.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 认证控制器
 */
@Api(tags = "认证管理")
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result<LoginResponse> login(@Validated @RequestBody LoginRequest request) {
        User user = userService.login(request.getUsername(), request.getPassword());
        if (user == null) {
            return Result.failed("用户名或密码错误");
        }
        LoginResponse response = new LoginResponse();
        response.setUserId(user.getId());
        response.setUsername(user.getUsername());
        response.setNickname(user.getNickname());
        response.setAvatar(user.getAvatar());
        response.setRole(user.getRole());
        // 这里应该生成JWT token，简化处理
        response.setToken("mock-token-" + System.currentTimeMillis());
        return Result.success(response);
    }

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public Result<User> register(@Validated @RequestBody RegisterRequest request) {
        // 校验两次密码是否一致
        if (!request.getPassword().equals(request.getConfirmPassword())) {
            return Result.failed("两次密码不一致");
        }
        try {
            User user = new User();
            BeanUtils.copyProperties(request, user);
            User registeredUser = userService.register(user);
            return Result.success(registeredUser);
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }
}